import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ToastService } from './toast.service';
import { mockPre } from 'config';
import { ApiResponse } from '../models/api';
import { Outlay } from '../models/outlay';

@Injectable({
  providedIn: 'root'
})
export class OutlayService {

  constructor(
    private $http: HttpClient,
    private toast: ToastService,
  ) { }

  apiPre = `${mockPre}/outlay`;

  list(): Observable<ApiResponse<Outlay[]>> {
    return this.$http.get<ApiResponse<Outlay[]>>(`${this.apiPre}/list`).pipe(
      catchError(err => this.handleError(err, 'outlay.api_list_failed'))
    );
  }
  info(id:string): Observable<ApiResponse<Outlay>> {
    return this.$http.get<ApiResponse<Outlay>>(`${this.apiPre}/${id}`).pipe(
      catchError(err => this.handleError(err, 'outlay.api_info_failed'))
    );
  }
  save(params: any): Observable<ApiResponse<any>> {
    return this.$http.post<ApiResponse<any>>(`${this.apiPre}/save`, { ...params }).pipe(
      catchError(err => this.handleError(err, 'outlay.api_save_failed'))
    );
  }
  update(params: any): Observable<ApiResponse<any>> {
    return this.$http.post<ApiResponse<any>>(`${this.apiPre}/update`, { ...params }).pipe(
      catchError(err => this.handleError(err, 'outlay.api_modify_failed'))
    );
  }
  delete(params: any): Observable<ApiResponse<any>> {
    return this.$http.post<ApiResponse<any>>(`${this.apiPre}/delete`, { ...params }).pipe(
      catchError(err => this.handleError(err, 'outlay.api_delete_failed'))
    );
  }

  private handleError(error: any, title: string, content?: string, param?: any): Observable<any> {
    this.toast.error(title, content, param);
    return throwError(error);
  }
}
